package org.example;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class Server {
    private static Map<String,Thread> threadMap =new HashMap<>();
    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象，指定监听的端口号
            ServerSocket serverSocket = new ServerSocket(Constant.port);
            System.out.println("服务器启动成功，部署在" + Constant.port + "端口，等待客户端连接...");
// 监听客户端的连接请求
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接：" + clientSocket.getInetAddress().getHostAddress());

                // 创建新线程来处理该客户端连接
               String id = String.valueOf(threadMap.keySet().size());
               Thread thread = new Thread(new ClientHandler(id, clientSocket));
                threadMap.put(id,thread);
                thread.start();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  private static class ClientHandler implements Runnable {
        private  String id;
        private final Socket clientSocket;
        private BufferedReader in;
        private PrintWriter out;
        private Server server;
        public ClientHandler(String id, Socket socket) {
            this.id = id;

            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try {
                // 获取输入流和输出流
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                out = new PrintWriter(clientSocket.getOutputStream(), true);

                String message;
                // 初始化变量，只执行一次，然后设置为false
                boolean initilize =true;
                while (true) {
                    // 读取客户端发送的信息
                    message = in.readLine();
                    ChatMessage chatMessage = analyseMessage(message);
                    if (chatMessage.getType().equals(ChatMessage.type.登出)) {
                        // 如果接收到终止标志，退出循环
                    }
                    if (chatMessage.getType().equals(ChatMessage.type.查询当前在线人员)) {
                        String nickname = chatMessage.getOrigin();
                        StringBuffer names =new StringBuffer();
                        threadMap.keySet(). forEach(s -> {
                            names.append(s);
                            names.append(" ， ");
                        });
                        out.println("当前在线总人数为：" +threadMap.keySet().size()+"，昵称为："+names);
                        // 如果接收到终止标志，退出循环
                    }
                    if (chatMessage.getType().equals(ChatMessage.type.查看自身状态)) {
                        sendMessage(out,"SERVER",id, ChatMessage.type.普通回应,String.format("你当前的昵称为：%s ，登录IP为：%s，登录端口为:%s。",id,clientSocket.getLocalAddress().getHostAddress(),clientSocket.getLocalPort()));
                        // 如果接收到终止标志，退出循环
                    }
                    if (chatMessage.getType().equals(ChatMessage.type.查询当前服务器状态)) {
                        // 如果接收到终止标志，退出循环
                    }
                    if (chatMessage.getType().equals(ChatMessage.type.发送私人消息)) {
                        // 如果接收到终止标志，退出循环
                    }
                    if (chatMessage.getType().equals(ChatMessage.type.广播)) {
                        // 如果接收到终止标志，退出循环
                    }
                    if (chatMessage.getType().equals(ChatMessage.type.设置昵称)) {
                        // 如果接收到终止标志，退出循环
                        this.id = chatMessage.getInformation();
                        sendMessage(out,"SERVER","YOU", ChatMessage.type.普通回应,"设置昵称成功，新昵称为："+this.id);
                    }
                    System.out.println("收到客户端消息：" + message.toString());

                    // 发送响应给客户端
                   // out.println("已收到你的消息：" + message.toString());

                    if(initilize)
                    {
                        sendMessage(out,"SERVER","YOU", ChatMessage.type.普通回应,"初始化成功，请使用nick命令设置名称");
                        initilize =false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭连接
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private ChatMessage analyseMessage(String message) {
            return JSON.parseObject(message,ChatMessage.class);

        }
      private static void sendMessage(PrintWriter out, String origin, String purpose, ChatMessage.type type, String message) {
          ChatMessage chatMessage = new ChatMessage(type,origin,purpose,message);
          out.println(JSON.toJSON(chatMessage));

      }

    }
}

